<template>
    <view class="my-votes-page">
        <!-- 顶部切换栏 -->
        <view class="top-tab-bar">
            <view class="top-tab" :class="{ active: currentTopTab === 'created' }" @click="currentTopTab = 'created'">
                我创建的
            </view>
            <view class="top-tab" :class="{ active: currentTopTab === 'joined' }" @click="currentTopTab = 'joined'">
                我参与的
            </view>
        </view>

        <!-- 二级标签栏 -->
        <view class="sub-tab-bar" v-if="currentTopTab === 'created'">
            <view class="sub-tab" :class="{ active: currentSubTab === 'all' }" @click="currentSubTab = 'all'">
                全部活动
            </view>
            <view class="sub-tab" :class="{ active: currentSubTab === 'notStart' }" @click="currentSubTab = 'notStart'">
                未开始
            </view>
            <view class="sub-tab" :class="{ active: currentSubTab === 'ongoing' }" @click="currentSubTab = 'ongoing'">
                进行中
            </view>
            <view class="sub-tab" :class="{ active: currentSubTab === 'ended' }" @click="currentSubTab = 'ended'">
                已结束
            </view>
        </view>

        <!-- 内容区域 -->
        <view class="content">
            <!-- 我创建的 - 全部活动 -->
            <view v-if="currentTopTab === 'created' && currentSubTab === 'all'">
                <view class="vote-item" v-for="item in createdAllList" :key="item.id" 
                    @click="jumpDetail(item.voteStatus,item.voteId)">
                    <view class="item-header">
                        <view class="item-title">{{ item.voteTitle }}</view>
                        <view class="tag">{{ item.voteType }}</view>
                    </view>
                    <view class="item-info">
                        <view class="status not-start">{{ item.voteStatus }}</view>
                        <view class="description">{{ item.description }}</view>
                    </view>
                    <view class="actions">
                        <view class="action-btn" @click.stop="addProject(item.voteId)">添加项目</view>
                        <view class="action-btn" @click.stop="openModal(item)">投票设置</view>
                        <view class="action-btn" @click.stop="handleShare(item)">分享转发</view>
                    </view>
                </view>
                <view class="end-mark" v-if="createdAllList.length > 0">--END--</view>
                <view class="create-btn" @click.stop="handleCreate">免费创建</view>
            </view>

            <!-- 我创建的 - 未开始 -->
            <view v-if="currentTopTab === 'created' && currentSubTab === 'notStart'">
                <view class="vote-item" v-for="item in createdNotStartList" :key="item.id"
                    @click="jumpDetail(item.voteStatus,item.voteId)">
                    <view class="item-header">
                        <view class="item-title">{{ item.voteTitle }}</view>
                        <view class="tag">{{ item.voteType }}</view>
                    </view>
                    <view class="item-info">
                        <view class="status not-start">{{ item.voteStatus }}</view>
                        <view class="description">{{ item.description }}</view>
                    </view>
                    <view class="actions">
                        <view class="action-btn" @click.stop="addProject(item.voteId)">添加项目</view>
                        <view class="action-btn" @click.stop="openModal(item)">投票设置</view>
                        <view class="action-btn" @click.stop="handleShare(item)">分享转发</view>
                    </view>
                </view>
                <view class="end-mark" v-if="createdNotStartList.length > 0">--END--</view>
                <view class="create-btn" @click.stop="handleCreate">免费创建</view>
            </view>

            <!-- 我创建的 - 进行中 -->
            <view v-if="currentTopTab === 'created' && currentSubTab === 'ongoing'">
                <view class="vote-item" v-for="item in createdOngoingList" :key="item.id"
                    @click="jumpDetail(item.voteStatus,item.voteId)">
                    <view class="item-header">
                        <view class="item-title">{{ item.voteTitle }}</view>
                        <view class="tag">{{ item.voteType }}</view>
                    </view>
                    <view class="item-info">
                        <view class="status not-start">{{ item.voteStatus }}</view>
                        <view class="description">{{ item.description }}</view>
                    </view>
                    <view class="actions">
                        <view class="action-btn" @click.stop="addProject(item.voteId)">添加项目</view>
                        <view class="action-btn" @click.stop="openModal(item)">投票设置</view>
                        <view class="action-btn" @click.stop="handleShare(item)">分享转发</view>
                    </view>
                </view>
                <view class="end-mark" v-if="createdOngoingList.length > 0">--END--</view>
                <view class="create-btn" @click.stop="handleCreate">免费创建</view>
            </view>

            <!-- 我创建的 - 已结束 -->
            <view v-if="currentTopTab === 'created' && currentSubTab === 'ended'">
                <view class="vote-item" v-for="item in createdEndedList" :key="item.id"
                    @click="jumpDetail(item.voteStatus,item.voteId)">
                    <view class="item-header">
                        <view class="item-title">{{ item.voteTitle }}</view>
                        <view class="tag">{{ item.voteType }}</view>
                    </view>
                    <view class="item-info">
                        <view class="status not-start">{{ item.voteStatus }}</view>
                        <view class="description">{{ item.description }}</view>
                    </view>
                    <view class="actions">
                        <view class="action-btn" @click.stop="addProject(item.voteId)">添加项目</view>
                        <view class="action-btn" @click.stop="openModal(item)">投票设置</view>
                        <view class="action-btn" @click.stop="handleShare(item)">分享转发</view>
                    </view>
                </view>
                <view class="end-mark" v-if="createdEndedList.length > 0">--END--</view>
                <view class="create-btn" @click.stop="handleCreate">免费创建</view>
            </view>

            <!-- 我参与的 -->
            <view v-if="currentTopTab === 'joined'">
                <view class="vote-item" v-for="item in joinedList" :key="item.id"
                    @click="jumpDetail(item.voteStatus,item.voteId)">
                    <view class="item-header">
                        <view class="item-title">{{ item.voteTitle }}</view>
                        <view class="tag">{{ item.voteType }}</view>
                    </view>
                    <view class="item-info">
                        <view class="status not-start">{{ item.voteStatus }}</view>
                        <view class="description">{{ item.description }}</view>
                    </view>
                    <view class="actions">
                        <view class="action-btn" @click.stop="addProject(item.voteId)">添加项目</view>
                        <view class="action-btn" @click.stop="handleShare(item)">分享转发</view>
                    </view>
                </view>
                <view class="end-mark" v-if="joinedList.length > 0">--END--</view>
                <view class="create-btn" @click.stop="handleCreate">免费创建</view>
            </view>
        </view>

        <!-- 底部导航栏 -->
        <view class="bottom-nav">
            <view class="nav-item" :class="{ active: currentNav === 'home' }" @click="switchToNav('home')">
                <view>首页</view>
            </view>
            <view class="nav-item" :class="{ active: currentNav === 'create' }" @click="switchToNav('create')">
                <view>创建投票</view>
            </view>
            <view class="nav-item" :class="{ active: currentNav === 'myVotes' }" @click="switchToNav('myVotes')">
                <view>我的投票</view>
            </view>
            <view class="nav-item" :class="{ active: currentNav === 'personal' }" @click="switchToNav('personal')">
                <view>个人中心</view>
            </view>
        </view>

        <!-- 模态框 -->
        <view class="modal" v-if="isModalVisible">
            <view class="modal-content">
                <view class="modal-header">
                    <view class="modal-title">投票设置</view>
                    <view class="modal-close" @click="closeModal">×</view>
                </view>
                <view class="modal-body">
                    <view class="form-group">
                        <label for="voteTitle">投票标题</label>
                        <input type="text" id="voteTitle" v-model="modalVoteTitle">
                    </view>
                    <view class="form-group">
                        <label for="voteType">投票类型</label>
                        <input type="text" id="voteType" v-model="modalVoteType">
                    </view>
                    <view class="form-group">
                        <label for="voteType">场外可投票数</label>
                        <input type="text" id="userVote1" v-model="modalVote1">
                    </view>
                    <view class="form-group">
                        <label for="voteType">场内可投票数</label>
                        <input type="text" id="userVote2" v-model="modalVote2">
                    </view>
                    <view class="form-group">
                        <label for="description">投票介绍</label>
                        <textarea id="description" v-model="modalDescription"></textarea>
                    </view>
                    <view class="form-group">
                        <label for="voteStatus">投票状态</label>
                        <input type="text" id="voteStatus" v-model="modalVoteStatus">
                    </view>
                </view>
                <view class="modal-footer">
                    <button class="btn btn-cancel" @click="closeModal">取消</button>
                    <button class="btn btn-save" @click="updateVotes">修改</button>
                </view>
            </view>
        </view>

        <!-- 分享弹框 -->
        <view class="share-modal" v-show="isShareModalOpen">
            <view class="modal-mask" @click="closeShareModal"></view>
            <view class="share-modal-content">
                <view class="modal-header">
                    <view class="close-btn" @click="closeShareModal">关闭</view>
                </view>
                <view class="share-content">
                    <image src="/static/img/go.jpg" mode="aspectFit" class="share-qr-code"></image>
                    <view class="share-tip">请截图将此二维码分享给您的朋友，一起为喜欢的作品投上宝贵一票吧!</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
    import {
        ref,
        onMounted
    } from 'vue';
    import {
        getVoteList,
        updateVote
    } from '@/api/vote.js';
    import {
        onShow
    } from '@dcloudio/uni-app';
    import { getAllProject, voteProject, cancelVoteProject, getRemainingVotes,setRemainingVotes,getVoteId } from '@/api/details.js';

    // 状态管理
    const currentTopTab = ref('created');
    const currentSubTab = ref('all');
    const currentNav = ref('myVotes');

    // 投票数据
    const createdAllList = ref([]);
    const createdNotStartList = ref([]);
    const createdOngoingList = ref([]);
    const createdEndedList = ref([]);
    const joinedList = ref([]);

    // 模态框状态
    const isModalVisible = ref(false);
    const modalVoteTitle = ref('');
    const modalVoteType = ref('');
    const modalVote1 = ref('');
    const modalVote2 = ref('');
    const modalDescription = ref('');
    const modalVoteStatus = ref('');
    const currentVoteId = ref(null);

    // 分享弹框状态
    const isShareModalOpen = ref(false);

    const userInfo = ref(null);

    // 获取投票列表
    const fetchVoteList = async () => {
        try {
            const response = await getVoteList({}); // 根据实际情况传递参数
            // 假设后端返回的数据格式为 { data: [投票列表] }
            const allVotes = response.data;

            // 获取当前用户 ID
            const userId = userInfo.value?.id;

            // 筛选自己创建的投票
            const myCreatedVotes = allVotes.filter(item => item.userId === userId);

            // 筛选"我创建的"不同状态的投票列表
            createdAllList.value = myCreatedVotes;
            createdNotStartList.value = myCreatedVotes.filter(item => item.voteStatus === '未开始');
            createdOngoingList.value = myCreatedVotes.filter(item => item.voteStatus === '进行中');
            createdEndedList.value = myCreatedVotes.filter(item => item.voteStatus === '已结束');

            // 筛选"我参与的"投票列表，排除自己创建的投票
            const otherParticipatedVotes = allVotes.filter(item => item.userId === "3" && item.userId !== userId);
            joinedList.value = [...myCreatedVotes,...otherParticipatedVotes];

            console.log(createdAllList.value);
        } catch (error) {
            console.error('获取投票列表失败:', error);
        }
    };

    // 打开模态框
    const openModal = (item) => {
        isModalVisible.value = true;
        modalVoteTitle.value = item.voteTitle;
        modalVoteType.value = item.voteType;
        modalVote1.value = item.userVote1;
        modalVote2.value = item.userVote2;
        modalDescription.value = item.description;
        modalVoteStatus.value = item.voteStatus;
        currentVoteId.value = item.voteId;
    };

    // 关闭模态框
    const closeModal = () => {
        isModalVisible.value = false;
    };

    // 保存修改
    const updateVotes = async () => {
        const voteChange = {
            voteId: currentVoteId.value,
            voteTitle: modalVoteTitle.value,
            voteType: modalVoteType.value,
            userVote1: modalVote1.value,
            userVote2: modalVote2.value,
            description: modalDescription.value,
            voteStatus: modalVoteStatus.value
        }
        console.log(voteChange);

        await updateVote(voteChange);
        fetchVoteList();
        closeModal();
    };

    // 导航切换
    const switchToNav = (navName) => {
        currentNav.value = navName;
        // 导航逻辑不变...
    };

    // 免费创建
    const handleCreate = () => {
        uni.navigateTo({
            url: '/pages/createVote/newVote'
        });
    };

    // 修改 jumpDetail 方法
    const jumpDetail = (voteStatus, voteId) => {
        if (voteStatus === '未开始') {
            uni.showToast({
                title: '投票未开始不能进入',
                icon: 'none'
            });
            return;
        }
        setRemainingVotes().then((data) => {
            // 处理剩余票数设置结果
        });
        getVoteId({ voteStatus: voteStatus }).then((data) => {
            uni.setStorageSync('voteId', data);
            console.log('voteId', data);
            uni.navigateTo({
                url: `/pages/details/details?voteStatus=${voteStatus}&voteId=${voteId}`
            });
        }).catch((error) => {
            console.error('获取投票ID失败:', error);
        });
    };

    // 添加项目（携带voteId）
    const addProject = (voteId) => {
        console.log('传递前的 voteId:', voteId); // 添加日志确认传递前的 voteId
        if (voteId) {
            uni.navigateTo({
                url: `/pages/projectAdd/projectAdd?voteId=${voteId}`
            });
            console.log(`跳转至项目添加页，voteId: ${voteId}`);
        } else {
            console.error('传递的 voteId 为 undefined');
        }
    };

    // 分享功能
    const handleShare = (item) => {
        isShareModalOpen.value = true;
    };
    
    // 关闭分享弹框
    const closeShareModal = () => {
        isShareModalOpen.value = false;
    };

    onShow(() => {
        userInfo.value = uni.getStorageSync("userInfo");
        fetchVoteList();
    });
</script>

<style scoped>
    .my-votes-page {
        width: 100%;
        min-height: 100vh;
        background-color: #f5f7fa;
        font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, Arial, sans-serif;
    }

    /* 顶部切换栏 */
    .top-tab-bar {
        display: flex;
        justify-content: center;
        background-color: #fff;
        border-bottom: 1px solid #e5e7eb;
    }

    .top-tab {
        flex: 1;
        text-align: center;
        padding: 12px 0;
        font-size: 16px;
        color: #666;
        background-color: transparent;
        border: none;
        cursor: pointer;
    }

    .top-tab.active {
        color: #f34b29;
        border-bottom: 2px solid #f34b29;
    }

    /* 二级标签栏 */
    .sub-tab-bar {
        display: flex;
        justify-content: center;
        background-color: #fff;
        border-bottom: 1px solid #e5e7eb;
    }

    .sub-tab {
        flex: 1;
        text-align: center;
        padding: 10px 0;
        font-size: 15px;
        color: #999;
        background-color: transparent;
        border: none;
        cursor: pointer;
    }

    .sub-tab.active {
        color: #333;
        border-bottom: 2px solid #333;
    }

    /* 内容区域 */
    .content {
        padding: 15px;
    }

    .vote-item {
        background-color: #fff;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 12px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    }

    .item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
    }

    .item-title {
        font-size: 17px;
        font-weight: 600;
        color: #333;
    }

    .tag {
        padding: 4px 8px;
        background-color: #d9f9e4;
        color: #28b760;
        font-size: 12px;
        border-radius: 6px;
    }

    .item-info {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        gap: 10px;
    }

    .description {
        font-size: 14px;
        color: #666;
    }

    .not-start {
        background-color: #ffe4e1;
        color: #f34b29;
    }

    .time-range {
        font-size: 14px;
        color: #666;
    }

    .stats {
        display: flex;
        gap: 12px;
        margin-bottom: 10px;
        color: #999;
        font-size: 13px;
    }

    .actions {
        display: flex;
        gap: 10px;
    }

    .action-btn {
        padding: 6px 12px;
        border: 1px solid #ddd;
        background-color: #fff;
        border-radius: 6px;
        cursor: pointer;
        font-size: 13px;
        color: #666;
    }

    .end-mark {
        text-align: center;
        color: #999;
        font-size: 13px;
        margin: 10px 0;
    }

    .create-btn {
        display: block;
        width: 150px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background-color: #f34b29;
        color: #fff;
        font-size: 16px;
        border: none;
        border-radius: 20px;
        margin: 20px auto 0;
        cursor: pointer;
    }

    /* 空状态 */
    .empty-tip {
        text-align: center;
        padding: 40px 0;
    }

    .empty-img {
        width: 70px;
        height: 70px;
    }

    /* 我参与的提示 */
    .joined-tip {
        text-align: center;
        color: #999;
        font-size: 14px;
        margin-bottom: 15px;
    }

    /* 底部导航栏 */
    .bottom-nav {
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 12px 0;
        background-color: #fff;
        border-top: 1px solid #e5e7eb;
        position: fixed;
        bottom: 0;
        left: 0;
        width: 100%;
    }

    .nav-item {
        text-align: center;
        color: #999;
        font-size: 12px;
        cursor: pointer;
    }

    .nav-item.active {
        color: #f34b29;
    }

    /* 模态框样式 */
    .modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .modal-content {
        background-color: #fff;
        border-radius: 8px;
        padding: 20px;
        width: 80%;
        max-width: 400px;
    }

    .modal-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
    }

    .modal-title {
        font-size: 18px;
        font-weight: 600;
    }

    .modal-close {
        font-size: 24px;
        cursor: pointer;
    }

    .modal-body {
        margin-bottom: 20px;
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-group label {
        display: block;
        margin-bottom: 5px;
        font-size: 14px;
        font-weight: 500;
    }

    .form-group input,
    .form-group textarea {
        width: 100%;
        padding: 8px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
    }

    .modal-footer {
        display: flex;
        justify-content: flex-end;
    }

    .btn {
        padding: 8px 16px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
    }

    .btn-cancel {
        background-color: #fff;
        border: 1px solid #ddd;
        color: #666;
        margin-right: 10px;
    }

    .btn-save {
        background-color: #f34b29;
        color: #fff;
    }

    /* 分享弹框样式 */
    .share-modal {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 9999;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .modal-mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .share-modal-content {
        position: relative;
        background-color: #fff;
        border-radius: 12px;
        width: 90%;
        max-width: 450px;
        padding: 30px 20px;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }

    .share-modal .modal-header {
        display: flex;
        justify-content: flex-end;
        margin-bottom: 20px;
    }

    .share-modal .close-btn {
        font-size: 16px;
        color: #666;
        padding: 5px 10px;
    }

    .share-content {
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .share-qr-code {
        width: 200rpx;
        height: 200rpx;
        margin-bottom: 20rpx;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .share-tip {
        font-size: 28rpx;
        color: #333;
        text-align: center;
        line-height: 1.5;
    }
</style>